package edu.gatech.doi.spamframework.parsers;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.jsoup.Jsoup;

/**
 * @author DE WANG
 *
 */

public class EmailParser {

	public static String html2text(String html) {    
		return Jsoup.parse(html).text();
	} 
	
	public EmailMessage parser(String filepath)
	{
//		String filename=System.getProperty("user.dir")+System.getProperties().getProperty("file.separator")+"290";
		File file=new File(filepath);
		
		FileInputStream fis;
		EmailMessage em=new EmailMessage();
		
		try {
			fis = new FileInputStream(filepath);
//			BufferedInputStream sbis=new BufferedInputStream(fis);
			fis.getFD();
			
//			InputStreamReader isr = new InputStreamReader(fis, "UTF8");
			
//			String content =null;
			Session s = Session.getDefaultInstance(new Properties()); 
//			InputStream is = new ByteArrayInputStream(content.getBytes()); 
			
			MimeMessage message = new MimeMessage(s, fis); 
			
			
			System.out.println(message.getDataHandler());
			
			
//			message.getAllHeaderLines(); 
//			message.getAllHeaders();
			int i=0;
			String lastheadervalue="";
			for (Enumeration<Header> e = message.getAllHeaders(); e.hasMoreElements();) { 
//				System.out.println(i);
//				System.out.println(e.nextElement());
				i++;
				Header h = e.nextElement(); 
//				
				em.getHeaderMap().put(h.getName().toUpperCase(), h.getValue());
			    System.out.println(h.getName()); 
			    System.out.println(h.getValue()); 
			    if(!e.hasMoreElements())
			    {
			    	lastheadervalue=lastheadervalue+h.getValue();
			    	System.out.println(lastheadervalue);
			    }
			}
			
//			message.getContent();
			Object o=null;
			try
			{
			o=message.getContent();
			//o=html2text((String)o);
			}
			catch(IOException ex)
			{
				FileReader fr=new FileReader(filepath);
				BufferedReader br=new BufferedReader(fr);
				StringBuffer sb=new StringBuffer();
				Boolean startcopy=false;
				String tempstr=null;
				while((tempstr=br.readLine())!=null)
				{
//					String tempstr=br.readLine();
					//System.out.println(tempstr);
					if(tempstr.contains(lastheadervalue.trim()))
					{
						startcopy=true;
					}
					if(startcopy)
					{
						sb.append(tempstr);
					}
				}
				o=sb.toString();
				o=html2text((String)o);
			}
			
			MimeMultipart mp;
			if(o instanceof  javax.mail.internet.MimeMultipart )
			{
				mp=(MimeMultipart) message.getContent();
			
			 
				 em.getBodyList().add(this.processMultipart(message.getContent()));
			 
//			System.out.println(mp.getBodyPart(1).getContent());
			}
			else if(o instanceof InputStream)
			{
				
			}
			else if(o instanceof String)
			{
				
				String str=(String) o;
				str=html2text(str);
				em.getBodyList().add(str);
				
				//System.out.println(str);
			}
			else
			{
				
			}
			
			
			em.getHeaderMap().put("ALLRECIPIENTS", message.getAllRecipients());
			
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
		}
		return em;
		
	}
	
	public String processMultipart(Object o)
	{
		System.out.print("**This is a Multipart Message.  ");
        Multipart mp = (Multipart)o;
        int count3;
        String multipartstr="";
		try {
			count3 = mp.getCount();
			System.out.println("It has " + count3 +
            " BodyParts in it**");
        for (int j = 0; j < count3; j++) {
            // Part are numbered starting at 0
            BodyPart b = mp.getBodyPart(j);
            String mimeType2 = b.getContentType();
//            System.out.println( "BodyPart " + (j + 1) +
//                                " is of MimeType " + mimeType);

            Object o2 = b.getContent();
            if (o2 instanceof String) {
                System.out.println("**This is a String BodyPart**");
                o2=html2text((String)o2);
                System.out.println((String)o2);
                multipartstr=multipartstr+(String)o2;
            }
            else if (o2 instanceof Multipart) {
                System.out.print(
                    "**This BodyPart is a nested Multipart.  ");
                Multipart mp2 = (Multipart)o2;
                int count2 = mp2.getCount();
                System.out.println("It has " + count2 +
                    "further BodyParts in it**");
             
                multipartstr=multipartstr+this.processMultipart(o2);
            }
            else if (o2 instanceof InputStream) {
                System.out.println(
                    "**This is an InputStream BodyPart**");
            }
        } //End of for
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return multipartstr;
	}
	
	public static void main(String [] args)
	{
		EmailParser ep=new EmailParser();
		String filename=System.getProperty("user.dir")+System.getProperties().getProperty("file.separator")+"datasets"+System.getProperties().getProperty("file.separator")+"trec"+System.getProperties().getProperty("file.separator")+"test"+System.getProperties().getProperty("file.separator")+"090";
		//System.out.println(ep.html2text("asdipghapsghapsodhgpoasdih"));
		ep.parser(filename);
	}


}
